<template>
  <div class="channelEdit">
    <!-- 我的频道 -->
    <div class="title">
      <div class="content">我的频道</div>
      <van-button @click="isEdit = !isEdit" size="mini" plain type="danger">{{
        isEdit ? '取消' : '编辑'
      }}</van-button>
    </div>
    <van-grid>
      <van-grid-item v-for="(item, index) in ownChannels" :key="item.id">
        <span @click="intoChannel(index)" :class="{ active: index == value }">{{
          item.name
        }}</span>
        <van-icon
          @click="deleteEdit(index, item)"
          v-if="isEdit && index"
          class="del-icon"
          name="cross"
        />
      </van-grid-item>
    </van-grid>

    <!-- 可选频道 -->
    <div class="title">
      <div class="content">可选频道</div>
    </div>
    <van-grid>
      <van-grid-item
        v-for="item in optionalChannel"
        :key="item.id"
        :text="item.name"
        @click="addChannel(item)"
      />
    </van-grid>
  </div>
</template>

<script>
import { setChannel } from '@/utils/storage.js'
import { addChannelAPI, delChannelAPI } from '@/api'
export default {
  data () {
    return {
      isEdit: false
    }
  },
  props: {
    //   我的频道
    ownChannels: {
      type: Array,
      required: true
    },
    // 所有频道
    allChannels: {
      type: Array,
      required: true
    },
    // 频道下标
    value: {
      type: Number
    }
  },
  methods: {
    //   进入频道
    intoChannel (index) {
      // 将下标传给外面的父组件
      this.$emit('input', index)
      // 通知父组件关闭sheet框
      this.$emit('close')
    },
    // 2. 点击可选添加频道
    async addChannel (item) {
      // 把被点的频道加到我的频道里
      this.ownChannels.push(item)
      // 判断是否有登录
      if (this.$store.state.tokenObj.token) {
        // 代表登录了
        await addChannelAPI({
          channels: [{ id: item.id, seq: this.ownChannels.length + 1 }]
        })
      } else {
        // 没登录,保存我的频道到本地
        setChannel(this.ownChannels)
      }
    },
    // 点击x删除我的频道的
    async deleteEdit (index, item) {
      this.ownChannels.splice(index, 1)
      // 判断删除的下标是否比选中的下标小，如果小需下标减一
      if (index < this.value) {
        this.$emit('input', this.value - 1)
      }
      // 判断是否登录
      if (this.$store.state.tokenObj.token) {
        // 登录了
        await delChannelAPI(item.id)
      } else {
        // 没登录保存到本地
        setChannel(this.ownChannels)
      }
    }
  },
  computed: {
    // 可选频道
    optionalChannel () {
      // 过滤所有频道
      return this.allChannels.filter(
        (value) => this.ownChannels.findIndex((v) => v.id === value.id) === -1
      )
    }
  }
}
</script>

<style lang="less" scoped>
.channelEdit {
  padding: 0 20px;
  .title {
    display: flex;
    justify-content: space-between;
    height: 60px;
    align-items: center;
  }
  .active {
    color: red;
  }
  .del-icon {
    position: absolute;
    top: 5px;
    right: 5px;
  }
}
</style>
